/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.FileTypeMap;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import sun.misc.JavaIOAccess;

/**
 *
 * @author berto
 */
public class MailSender {
    
    /*
     * ContentType list
     * http://webdesign.about.com/od/multimedia/a/mime-types-by-content-type.htm
     * 
     */
    public static String TYPE_PDF="application/pdf";
    public static String TYPE_PNG="image/png";
    
    public static void main(String args[]){
        String text="Vediamo se l'invio delle email funziona...\n"
                + "http://3.bp.blogspot.com/-MQnMB-yMlxg/T8-CCL_N91I/AAAAAAAABS8/vPMl-DXINo4/s1600/Break_your_Limits_.jpg"
                + "Nel caso andra' tutto bene sono un mito!\n\n"
                + "Cordiali saluti \n"
                + "Daghen De Pu";
        /*MailSender.sendTextMailWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", 
                "daghen.de.pu@gmail.com", "Lorenzo.Bertoldi.1991@gmail.com", 
                "Link", text);
         */
        byte[] bytes=null;
        String path="./web/immagini/themplate/logo.png";
        DataSource data=new FileDataSource(path);
        try {
            data=new FileDataSource(path);
            FileInputStream fis = new FileInputStream(path);
            //System.out.println(file.exists() + "!!");
            //InputStream in = resource.openStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
            bytes = bos.toByteArray();
        } catch (IOException ex) {
            System.err.println(ex);
        }
        MailSender.sendMailWithAttachementsWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", 
                "daghen.de.pu@gmail.com", "Lorenzo.Bertoldi.1991@gmail.com", 
                "Allegato da: Path", text, path);
        MailSender.sendMailWithAttachementsWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", 
                "daghen.de.pu@gmail.com", "Lorenzo.Bertoldi.1991@gmail.com", 
                "Allegato da: DataSource", text,data);
        MailSender.sendMailWithAttachementsWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", 
                "daghen.de.pu@gmail.com", "Lorenzo.Bertoldi.1991@gmail.com", 
                "Allegato da: Array di byte", text,bytes,"Logo",TYPE_PNG);
        
    }
    
    private static Session getSessionUniTNFromOut(String username,String psw){
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp_server_universita_da_fuori");
            props.put("mail.smtp.port","587");
            props.put("mail.smtp.debug", "true");
            props.put ("mail.smtp.starttls.enable", "true");
            
            props.put("mail.smtp.socketFactory.port", "587");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            
            props.put("mail.debug", "true");
            props.put("mail.transport.protocol", "smtp");
            
            
            final String finalUsername=username;
            final String finalPsw=psw;
            java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Authenticator auth = new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication(){
                        return new PasswordAuthentication(finalUsername, finalPsw);
                    }
                };
            return Session.getInstance(props,auth);
    }
    
    public static void sendTextMailWithUniTNfromOut(String username,String psw,
        String fromEmailUni,String recipients, String subject,String text){
        try{
            Session s=getSessionUniTNFromOut(username, psw);
            
            MimeMessage message = new MimeMessage(s);
            InternetAddress from = new InternetAddress(fromEmailUni);
            message.setFrom(from);
            InternetAddress to = new InternetAddress(recipients);
            message.addRecipient(Message.RecipientType.TO, to);
            message.setSubject(subject);
            message.setText(text);
            message.saveChanges();
            //Doppia autenticazione (Anche sull'invio oltre che nella sessione)
            Transport transport = s.getTransport("smtp");
            transport.connect("smtp-auth.bris.ac.uk",username,psw);
            transport.sendMessage(message,message.getAllRecipients());
            transport.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
     private static Session getSessionWithAutentication(String fromEmail,
            String username,String psw){
            // Get a Properties object
            Properties props = System.getProperties();
            if(fromEmail.endsWith("yahoo.com")){
                props.setProperty("mail.smtp.host", "smtp.mail.yahoo.com");
            }else if(fromEmail.endsWith("gmail.com")){
                props.setProperty("mail.smtp.host", "smtp.gmail.com");
            }
            props.setProperty("mail.smtp.port", "465");
            
            props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            props.put("mail.debug", "true" );
            
            final String finalUsername = username;
            final String finalPassword = psw;
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Authenticator auth = new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication(){
                        return new PasswordAuthentication(finalUsername, finalPassword);
                    }
                };
            
            return Session.getDefaultInstance(props, auth);
    }
    
    public static void sendTextMailWithUniTNfromUni(String fromUni,String recipients,
            String subject,String text){
        try{
            Properties props = System.getProperties();
            props.put( "mail.smtp.host", "mail.unitn.it" );
            props.put( "mail.debug", "true" );
            Session session = Session.getDefaultInstance( props );
            Message message =composeTextMail(session, fromUni, recipients, subject, text);
            Transport.send(message);
        }catch(Exception ex){
            System.out.println(ex);
            ex.printStackTrace();
        }
    }
    
    public static void sendTextMailWithAutentication(String username,String psw,
            String fromEmail,String recipients, String subject,String text){
        try{
            Session session=getSessionWithAutentication(fromEmail, username, psw);
            // — Create a new message –
            Message message=composeTextMail(session, fromEmail, recipients, subject, text);
            Transport.send(message);
        }catch(Exception ex){
            System.out.println(ex);
            ex.printStackTrace();
        }
    }
    
    private static Message composeTextMail(Session session,String fromEmail, 
            String recipients, String subject,String text) throws MessagingException{
            // — Create a new message –
            Message msg = new MimeMessage(session);
            // — Set the FROM and TO fields –
            msg.setFrom(new InternetAddress(fromEmail));
            msg.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(recipients,false));
            msg.setSubject(subject);
            msg.setText(text);
            msg.setSentDate(new Date());
            return msg;
    }
    
    private static Message composeMessageWithAttachements(Session session,
            String fromEmail,String recipients,String subject,String text, Object... files) throws AddressException, MessagingException{
            Message message = new MimeMessage( session );
            InternetAddress from = new InternetAddress( fromEmail );
            InternetAddress to[] = InternetAddress.parse( recipients,false );
            message.setFrom( from );
            message.setRecipients( Message.RecipientType.TO, to );
            message.setSentDate( new Date() );
            message.setSubject( subject );
            Multipart multipart = new MimeMultipart();
            //crea la parte testuale
            BodyPart messageBodyPartText = new MimeBodyPart();
            messageBodyPartText.setText(text);
            //aggiunge la parte testuale
            multipart.addBodyPart( messageBodyPartText );
            
            for(Object file:files){
                //crea l'allegato
                DataSource dataSource;
                if(file.getClass()==String.class){
                    dataSource = new FileDataSource( (String)file );
                }else if(DataSource.class.isAssignableFrom(file.getClass())){
                    dataSource=(DataSource)file;
                }else{
                    throw new ClassFormatError("L'allegato puo' rappresentare solo una stringa, o il datasource");
                }
                BodyPart messageBodyPartData = new MimeBodyPart();
                messageBodyPartData.setDataHandler( new DataHandler(dataSource) );
                messageBodyPartData.setFileName( dataSource.getName());
                //aggiunge l'allegato all'oggetto multipart
                multipart.addBodyPart( messageBodyPartData);
            }
            //imposta come contenuto del messaggio l'oggetto multipart
            message.setContent(multipart);
            return message;
    }
    
    public static void sendMailWithAttachmentsWithUniTnfromUni(String fromEmailUni,
            String recipients,String subject,String text, Object... files){
        try{
            Properties props = System.getProperties();
            props.put( "mail.smtp.host", "mail.unitn.it" );
            Session session = Session.getDefaultInstance( props );
            Message message=composeMessageWithAttachements(session, fromEmailUni, recipients, subject, text, files);
            Transport.send(message);
        }catch(Exception ex){
            System.out.println(ex);
            ex.printStackTrace();
        }
    }
    
     public static void sendMailWithAttachementsWithAutentication(String username,String psw,
            String fromEmail,String recipients, String subject,String text,Object... files){
        try{
            Session session=getSessionWithAutentication(fromEmail, username, psw);
            // — Create a new message –
            Message message=composeMessageWithAttachements(session, fromEmail, recipients, subject, text, files);
            Transport.send(message);
        }catch(Exception ex){
            System.out.println(ex);
            ex.printStackTrace();
        }
    }
     
     public static void sendMailWithAttachementsWithAutentication(String username,String psw,
            String fromEmail,String recipients, String subject,String text, byte[] bytes,String name,String type) {
        ByteArrayDataSource byteArrayDataSource=new ByteArrayDataSource(bytes, type);
        byteArrayDataSource.setName(name);
        DataSource data=byteArrayDataSource;
        sendMailWithAttachementsWithAutentication(username, psw, fromEmail, recipients, subject, text, data);
    }
     
    public static void sendMailWithAttachementsWithUniTNfromOut(String username,String psw,
        String fromEmailUni,String recipients, String subject,String text,Object... files){
        try{
            Session s=getSessionUniTNFromOut(username, psw);
            Message message=composeMessageWithAttachements(s, fromEmailUni, recipients, subject, text, files);
            message.saveChanges();
            //Doppia autenticazione (Anche sull'invio oltre che nella sessione)
            Transport transport = s.getTransport("smtp");
            transport.connect("smtp-auth.bris.ac.uk",username,psw);
            transport.sendMessage(message,message.getAllRecipients());
            transport.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    
}
